package com.example.base.fragment;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;

import android.view.View;
import android.view.ViewGroup;

import android.widget.AdapterView;
import android.widget.ImageView;


import com.bumptech.glide.Glide;
import com.example.base.Utils.OkHttpUtil;
import com.example.base.adapter.BannerAdapter;
import com.example.base.sqllite.MySQLite;
import com.example.base.view.BannerViewPager;
import com.example.base.bean.Data;
import com.example.base.bean.Home;
import com.example.base.bean.HomeThree;
import com.example.base.adapter.MyAdapter;
import com.example.base.view.NestedListview;
import com.example.base.bean.Object;
import com.example.base.R;
import com.example.base.activity.WebViewActivity;
import com.google.gson.Gson;


import java.io.IOException;

import java.text.SimpleDateFormat;
import java.util.ArrayList;

import java.util.Date;
import java.util.List;


import okhttp3.Request;

/**
 * A simple {@link Fragment} subclass.
 * create an instance of this fragment.
 */
public class HomeFragment extends Fragment {
  private Context context;
  private BannerViewPager mBannerVp;
  private NestedListview listView;
  private List<HomeThree> dataList = new ArrayList<>();
  private MyAdapter mAdapter;
  private String uri = "https://www.wanandroid.com/article/list/";
  private int number = 1;
  private String uri2 = "/json";
  private ImageView imageView;

  public HomeFragment() {
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                           Bundle savedInstanceState) {
    View inflate = inflater.inflate(R.layout.fragment_home, container, false);
    initView(inflate);
    initListener();
    getDataFromNet();
    initHomeView();
    return inflate;
  }


  private void getDataFromNet() {
    sendBannerRequestWithokhttp();
    sendListRequestWithokhttp();
    sendListRefreshRequestWithokhttp();
    sendListLoadMoreRequestWithokhttp();
    Log.i("gx", "getDataFromNet: 更新");
  }

  private void sendListLoadMoreRequestWithokhttp() {
    OkHttpUtil.getAsync(uri + number + uri2, new OkHttpUtil.DataCallBack() {
      @Override
      public void requestFailure(Request request, IOException e) {

      }

      @Override
      public void requestSuccess(String result) throws Exception {
        Gson gson = new Gson();
        Home home = gson.fromJson(result, Home.class);
        refreshListView(home);
      }
    });
  }

  private void sendListRefreshRequestWithokhttp() {
    OkHttpUtil.getAsync(uri + 0 + uri2, new OkHttpUtil.DataCallBack() {
      @Override
      public void requestFailure(Request request, IOException e) {

      }

      @Override
      public void requestSuccess(String result) throws Exception {
        Gson gson = new Gson();
        Home home = gson.fromJson(result, Home.class);
        refreshListViewup(home);
      }
    });
  }

  private void sendListRequestWithokhttp() {
    OkHttpUtil.getAsync(uri + 0 + uri2, new OkHttpUtil.DataCallBack() {
      @Override
      public void requestFailure(Request request, IOException e) {

      }

      @Override
      public void requestSuccess(String result) throws Exception {
        Gson gson = new Gson();
        Home home = gson.fromJson(result, Home.class);
        refreshListView(home);
      }
    });
  }

  private void initListener() {
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
      @Override
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        List<HomeThree> dataList = mAdapter.getDataList();
        ContentValues cv = new ContentValues();
        cv.put("title", dataList.get(position).getShareUser());
        cv.put("text", dataList.get(position).getTitle());
        cv.put("link", dataList.get(position).getLink());
        SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        cv.put("time", s.format(new Date()));


        MySQLite user = new MySQLite(context, "user", null, 1);
        SQLiteDatabase db = user.getWritableDatabase();

        long row = db.insert("history", null, cv);
        Log.i("homefragment", row + "");
        db.close();
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.putExtra("Url", dataList.get(position).getLink());
        startActivity(intent);
      }
    });
    imageView.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        getFragmentManager().beginTransaction()
                            .addToBackStack(null)
                            .replace(R.id.main, new SearchFragment()).commit();
      }
    });
  }

  private void initView(View inflate) {
    mBannerVp = inflate.findViewById(R.id.banner_vp);
    listView = inflate.findViewById(R.id.listview1);
    imageView = inflate.findViewById(R.id.img_home_serach);
    context = getContext();
  }

  private void sendBannerRequestWithokhttp() {
//        OkHttpClient mOkHttpClient = new OkHttpClient();
//        Request request = new Request.Builder()
//                .url("https://www.wanandroid.com/banner/json")
//                .get()
//                .build();
//        Call call = mOkHttpClient.newCall(request);
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(@NotNull Call call, @NotNull IOException e) {
//            }
//
//            @Override
//            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
//                if (response.isSuccessful()) {
//                    Gson gson = new Gson();
//                    String htmlStr = response.body().string();
//                    Object object = gson.fromJson(htmlStr, Object.class);
//                    initBanner(object.getData());
//                }
//            }
//        });
    OkHttpUtil.getAsync("https://www.wanandroid.com/banner/json", new OkHttpUtil.DataCallBack() {
      @Override
      public void requestFailure(Request request, IOException e) {

      }

      @Override
      public void requestSuccess(String result) throws Exception {
        Gson gson = new Gson();
        String bannerdata = result;
        Object object = gson.fromJson(bannerdata, Object.class);
        initBanner(object.getData());
      }
    });
//        OkHttpClient mOkHttpClient2 = new OkHttpClient();
//        Request request2 = new Request.Builder()
//                .url(uri+0+uri2)
//                .get()
//                .build();
//        Call call2 = mOkHttpClient2.newCall(request2);
//        call2.enqueue(new Callback() {
//            @Override
//            public void onFailure(@NotNull Call call, @NotNull IOException e) {
//            }
//            @Override
//            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
//                if (response.isSuccessful()) {
//                    Gson gson = new Gson();
//                    Home home = gson.fromJson(response.body().string(), Home.class);
//                    getActivity().runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            refreshListView(home);
//                        }
//                    });
//                }
//            }
//        });
  }

  private void refreshListView(Home home) {
    List<HomeThree> data = home.getData().getDatas();
    mAdapter.setData(data);
    mAdapter.notifyDataSetChanged();
  }

  private void refreshListViewup(Home home) {
    List<HomeThree> data = home.getData().getDatas();
    mAdapter.setData_up(data);
    mAdapter.notifyDataSetChanged();
  }

  private void initHomeView() {
    mAdapter = new MyAdapter(context, dataList);
    listView.setAdapter(mAdapter);
    listView.setOnLoadMoreListener(new NestedListview.OnLoadMoreListener() {
      @Override
      public void onloadMore() {
        loadMore(number);
        number++;
      }
    });
    listView.setOnRefreshListener(new NestedListview.OnRefreshListener() {
      @Override
      public void refreshData() {
        refresh();
      }
    });
  }

  private void refresh() {
    new Thread() {
      @Override
      public void run() {
        super.run();
        try {
          Thread.sleep(2000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        sendListRefreshRequestWithokhttp();
        getActivity().runOnUiThread(new Runnable() {
          @Override
          public void run() {
            mAdapter.notifyDataSetChanged();
            listView.onRefreshComplate();
          }
        });
      }
    }.start();
  }

  private void initBanner(List<Data> data) {
    getActivity().runOnUiThread(new Runnable() {
      @Override
      public void run() {
        mBannerVp.setAdapter(new BannerAdapter() {
          @Override
          public View getView(int position) {
            ImageView bannerlv = new ImageView(context);
            String imagePath2 = data.get(position).getImagePath();
            Glide.with(context).load(imagePath2).into(bannerlv);
            return bannerlv;
          }
        });
        mBannerVp.startRoll();
      }
    });
  }

  private void loadMore(int number) {
    new Thread() {
      @Override
      public void run() {
        super.run();
        try {
          Thread.sleep(2000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        sendListLoadMoreRequestWithokhttp();
        getActivity().runOnUiThread(new Runnable() {
          @Override
          public void run() {
            mAdapter.notifyDataSetChanged();
            listView.setLoadCompleted();
          }
        });
      }
    }.start();

  }
}